package cn.teaseed.view;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.teaseed.Main;
import cn.teaseed.comn.CorsParam;
import cn.teaseed.comn.JobEntity;
import cn.teaseed.comn.ModelMap;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

@Data
@Slf4j
@Component
public class ModelSearchView implements Initializable {

    public ComboBox<String> modName;
    public TableView<ModelMap> tableList;
    public TableColumn<ModelMap, String> address;
    public TableColumn<ModelMap, String> name;
    private Map<String, Map<String, String>> map;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        name.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        address.setCellValueFactory(cellData -> cellData.getValue().addressProperty());

        //菜单配置
        ContextMenu contextMenu = new ContextMenu();
        MenuItem deleteItem = new MenuItem("复制");
        deleteItem.setOnAction(event -> {
            ModelMap modelMap = tableList.getSelectionModel().getSelectedItem();
            ClipboardContent content = new ClipboardContent();
            content.putString(modelMap.getAddress());
            Clipboard.getSystemClipboard().setContent(content);
        });
        ObservableList<MenuItem> items = contextMenu.getItems();
        items.add(deleteItem);
        // 为TableView设置右键菜单
        tableList.setOnMouseClicked(event -> {
            //显示右键菜单
            if (event.getButton() == MouseButton.SECONDARY && event.getClickCount() == 1) {
                if (!tableList.getSelectionModel().isEmpty()) {
                    contextMenu.show(tableList, event.getScreenX(), event.getScreenY());
                }
            }
            //左键关闭菜单
            if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 1) {
                if (!tableList.getSelectionModel().isEmpty()) {
                    contextMenu.hide();
                }
            }
        });

        //获取当前登录信息
        Properties properties = System.getProperties();
        String homeUrl = properties.get("user.home").toString();
        String s = "\\AppData\\LocalLow\\VRChat\\VRChat\\OSC";
        //搜索所有OSC模型配置JSON文件
        List<File> allOSCFile = new ArrayList<>();
        File[] ls = FileUtil.ls(homeUrl + s);
        for (File l : ls) {
            List<File> files = FileUtil.loopFiles(l, pathname -> {
                String type = FileTypeUtil.getType(pathname);
                return type.equals("json");
            });
            allOSCFile.addAll(files);
        }

        if (allOSCFile.size() > 100) log.error("模型列表过长");

        //便利搜索可用数据
        map = new HashMap<>();
        allOSCFile.forEach(e -> {
            try (InputStream jsonInput = Files.newInputStream(e.toPath())) {
                byte[] bytes = IoUtil.readBytes(jsonInput);
                jsonInput.close();
                String jsonStr = new String(bytes, StandardCharsets.UTF_8);

                String modelName = (String) new JSONObject(jsonStr).getByPath("$.name");
                JSONArray outList = (JSONArray) new JSONObject(jsonStr).getByPath("$.parameters");
                Map<String, String> data = new HashMap<>();
                outList.forEach(jo -> {
                    JSONObject obj = (JSONObject) jo;
                    if (obj.get("output") != null) {
                        String modName = (String) obj.get("name");
                        JSONObject output = (JSONObject) obj.get("output");
                        String modAddress = (String) output.get("address");
                        data.put(modName, modAddress);
                    }
                });
                map.put(modelName, data);
            } catch (IOException es) {
                log.error("模型文件[{}]加载失败", e.getName());
            }
        });
        modName.getItems().setAll(map.keySet());
    }

    public void showList(ActionEvent actionEvent) {
        String value = modName.getValue();
        Map<String, String> stringStringMap = map.get(value);

        List<ModelMap> list = stringStringMap.entrySet().stream()
                .map(entry -> new ModelMap(entry.getValue(), entry.getKey()))
                .collect(Collectors.toList());

        ObservableList<ModelMap> data = FXCollections.observableArrayList();
        data.addAll(list);

        tableList.setItems(data);
    }
}

